<!--租客签约账单预览对话框-->
<template>
	<a-modal v-bind="option" class="renter-bill-preview-dialog">
		<vxe-toolbar v-if="from !== 'import'">
			<template #buttons>
				<!-- 自然月才可合并首尾账单 -->
				<template v-if="entity.cycleType === 2 && entity.activitySelected?.length === 0">
					<a-checkbox :checked="entity.mergeType === 3" @click="onMergeChange">是否合并首尾月账单</a-checkbox>
				</template>
				<template v-if="entity.deductionAmount < 0">
					<a-checkbox v-model:checked="entity.carryForward" @change="getRenterContractPreview">
						可结转抵扣金额{{ Math.abs(entity.deductionAmount).toLocaleString() }}元，是否抵扣至新合同
					</a-checkbox>
				</template>
			</template>
			<template v-if="!includedCarryForward && from !== 'import'" #tools>
				<div v-action="['mk_contract_tenant_muti_preview']"  >
					已收账单支付方式：
					<a-select
					v-model:value="entity.paymentMethod"
					:options="options.payMethods"
					placeholder="请选择支付方式"
					style="width: 150px"
					:field-names="DEFAULT_FIELD_NAME" />
				</div>
			</template>
		</vxe-toolbar>
		<div class="bill-table-wrapper">
			<a-skeleton :loading="loadings.calc" active :paragraph="{rows: 13}">
				<template v-for="item in list" :key="item.num">
					<a-typography-paragraph strong>
						<blockquote>
							{{ item.name }}
							<small   v-action="['mk_contract_tenant_muti_preview']" v-if="!includedCarryForward && from !== 'import'" v-color="{color: 'warning'}">
								（勾选账单，该账单将自动处理生成流水！）
							</small>
							<template v-if="item.name.includes('租金') && entity.activitySelected?.length > 0">
								<a-tooltip overlayClassName="tooltip-active-wrapper" color="#fff" placement="topLeft" arrowPointAtCenter>
									<small v-color="{color: 'primary'}" style="margin-left: 10px">
										已参与{{ entity.activitySelected?.length }}项优惠
									</small>
									<template #title>
										<div class="tooltip-active-item" v-for="active in entity.activitySelected" :key="active.id">
											<!-- <small>{{ active.type === 4 ? '付款优惠' : '优惠活动' }}</small> -->
											<b v-color="{color: 'primary'}">{{ active.name }}</b>
											<!-- 立减描述 合同周期大于 X 个月，立减 X 元 -->
											<small v-if="active.type === 1" v-color="{color: 'warning'}">
												（合同周期大于{{ active.useThreshold }}个月，立减{{ active.discountAmount }}元！）
											</small>
											<!-- 折扣描述 合同周期大于 X 个月，租期内 或 前 或 后 打 X 折 或 上浮 x% 或 不打折  -->
											<small v-else-if="active.type === 2" v-color="{color: 'warning'}">
												（合同周期大于{{ active.useThreshold }}个月，{{
													active?.detailedTimePeriod === 0
														? '租期内'
														: active.detailedTimePeriod > 0
														? `后${Math.abs(active.detailedTimePeriod)}个月`
														: `前${Math.abs(active.detailedTimePeriod)}个月` || ''
												}}租金{{
													active.discountAmount === 100
														? '不打折'
														: active.discountAmount > 100
														? '上浮'
														: '折扣'
												}}{{ active.discountAmount > 100 ? active.discountAmount - 100 : active.discountAmount
												}}{{ active.discountAmount === 100 ? '' : '%' }}！）
											</small>
											<!-- 付款优惠描述 付款方式为 X ，，每月租金 打 X 折 或 上浮 x% 或 不打折  -->
											<small v-else-if="active.type === 4" v-color="{color: 'warning'}">
												（付款方式为{{ payDiscount[getPayType(entity.periodMonth)] }}，每月租金{{
													payDiscountNum(active) === 100
														? '不打折'
														: payDiscountNum(active) > 100
														? '上浮'
														: '折扣'
												}}{{
													payDiscountNum(active) === 100
														? ''
														: payDiscountNum(active) > 100
														? payDiscountNum(active) - 100
														: payDiscountNum(active)
												}}{{ payDiscountNum(active) === 100 ? '' : '%' }}！）
											</small>
										</div>
									</template>
								</a-tooltip>
							</template>
						</blockquote>
					</a-typography-paragraph>
					<vxe-table :data="item.bills" v-bind="billTableOption" class="bill-preview-table">
						<!--结转抵扣不显示复选框-->
						<vxe-column   v-action="['mk_contract_tenant_muti_preview']" v-if="!includedCarryForward && from !== 'import'" type="checkbox" width="65" />
						<vxe-column type="expand" title="期数" width="100">
							<template #default="{row}">第{{ row.num }}期</template>
							<template #content="{row}">
								<vxe-table :data="row.finances" :show-header="false">
									<vxe-column width="65">
										<template #default="{row: detail}">
											<svg-icon :icon-class="`finance-${detail.feeDirection == 1 ? 'in' : 'out'}`" />
											<span v-if="detail.feeDirection === 1" v-color="{color: 'primary'}">&nbsp;收</span>
											<span v-else v-color="{color: 'danger'}">&nbsp;付</span>
										</template>
									</vxe-column>
									<vxe-column min-width="200">
										<template #default="{row: detail}">
											{{ detail.feeSubjectName }}:
											<span v-color="{color: 'primary'}">{{ detail.amount.toLocaleString() }}</span>
											元
											<!--billType=2定金账单，不显示抵扣信息-->
											<template v-if="row.billType !== 2 && detail.occurredMoney > 0 && detail.feeDirection === 1">
												<a-tag color="processing" class="bill-carry-forward-tips">
													结转抵扣
													{{ detail.occurredMoney.toLocaleString() }}
													元， 抵扣后待收
													{{ detail.notOccurredMoney.toLocaleString() }}
													元
												</a-tag>
											</template>
											<a-tag v-if="detail.comment" color="processing" class="bill-carry-forward-tips activity-tag">
												{{ detail.comment }}
											</a-tag>
										</template>
									</vxe-column>
									<vxe-column width="180">
										<template #default="{row}">付款日期:{{ row.payDate }}</template>
									</vxe-column>
									<vxe-column width="280">
										<template #default="{row}">费用周期:{{ row.beginDate }}至{{ row.endDate }}</template>
									</vxe-column>
								</vxe-table>
							</template>
						</vxe-column>
						<vxe-column field="billDate" title="账单日期" min-width="120" align="center" />
						<vxe-column title="账单周期" min-width="260" align="center">
							<template #default="{row}">{{ row.beginDate }}至{{ row.endDate }}</template>
						</vxe-column>
						<vxe-column field="totalAmount" title="金额" min-width="100" align="right">
							<template #default="{row}">{{ row.totalAmount.toLocaleString() }}</template>
						</vxe-column>
						<vxe-column title="操作" width="100" align="center">
							<template #default="{row}">
								<a>明细</a>
							</template>
						</vxe-column>
					</vxe-table>
				</template>
			</a-skeleton>
		</div>
		<template #footer>
			<slot v-if="from === 'import'" name="import_slot" :contract="contract" :billList="list"></slot>
			<template v-else>
				<a-tooltip v-if="props.contract.contractMedium === 1 && props.contract.signType === 1" color="#fff" placement="topRight">
					<template #title>
						<div class="footer-tip" v-color="{color: COLOR_MAP.danger}">注意:</div>
						<div class="footer-tip" v-color="{color: COLOR_MAP.default}">
							1、保存后需在一小时内完善合同附件并上传， 否则合同失效。
						</div>
						<div class="footer-tip" v-color="{color: COLOR_MAP.default}">2、当前仅保存，需完善合同并完成上传后合同才能生效</div>
					</template>
					<question-circle-outlined v-color="{color: COLOR_MAP.danger}" class="footer-ico" />
				</a-tooltip>
				<a-button
					v-if="props.contract.contractMedium === 1 && props.contract.signType === 1"
					type="primary"
					@click="submit(1)"
					:loading="loadings.paperSave"
					:disabled="loadings.calc || loadings.disabledPaperSave">
					保存纸质合同
				</a-button>
				<a-button type="primary" :loading="loadings.save" :disabled="loadings.calc || loadings.disabledSave" @click="submit(0)">
					保存
				</a-button>
			</template>
		</template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {QuestionCircleOutlined} from '@ant-design/icons-vue'
	import {computed, reactive, ref, toRaw, toRef, watch} from 'vue'
	import settingApi from 'yuxin-base/src/api/setting-api'
	import {DEFAULT_FIELD_NAME, DIC_PID_MAP} from 'yuxin-base/src/constant'
	import {VxeTableProps} from 'vxe-table'
	import {RenterContract} from '@/interface/contract'
	import {
		renterContractChange,
		renterContractInsert,
		renterContractPreview,
		renterContractReset,
		renterContractResubmit,
		renterContractSublease
	} from '@/api/contract'
	import {message} from 'ant-design-vue'
	import {COLOR_MAP} from 'yuxin-base/src/constant'
	import XEUtils from 'xe-utils'

	const props = defineProps<{
		visible: boolean
		contract: RenterContract
		from?: string
	}>()

	const entity = toRef(props, 'contract')

	const loadings = reactive({
		calc: false,
		save: false,
		// 纸质合同保存按钮loading
		paperSave: false,
		disabledSave: false,
		disabledPaperSave: false
	})

	const payDiscount = {
		annualPayment: '年付',
		quarterlyPayment: '季付',
		semiAnnualPayment: '半年付'
	}
	const getPayType = type => {
		let count = type
		const {leasePeriod} = props.contract
		if ((leasePeriod as number) < type) count = leasePeriod
		switch (count) {
			case 1:
			case 2:
			case 3:
			case 4:
			case 5:
				return 'quarterlyPayment'
			case 6:
			case 7:
			case 8:
			case 9:
			case 10:
			case 11:
				return 'semiAnnualPayment'
			case 12:
			case 99:
				return 'annualPayment'
			default:
				return ''
		}
	}
	const payDiscountNum = item => {
		return JSON.parse(item.payDiscount)[getPayType(entity.value.periodMonth)]
	}

	const emits = defineEmits(['update:visible', 'success'])
	const option = reactive({
		width: 1100,
		title: '账单预览',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('update:visible', false)
		}
	})

	// 账单列表
	const list = ref<any[]>([])

	watch(
		() => props.visible,
		() => {
			if (props.visible) {
				console.log(props.contract, props.contract.contractMedium)
				getDics()

				entity.value.mergeType = null
				entity.value.carryForward = false
				entity.value.paymentMethod = null

				// 换房合同重新提交获取结转金额
				// if ((entity.value.reset || entity.value.resubmit) && entity.value.contractPid && entity.value.signType === 4) {
				// 	renterContractCarryForwardPrice(entity.value.contractPid).then(({data}) => {
				// 		entity.value.deductionAmount = -data
				// 	})
				// }

				getRenterContractPreview()
			}
		}
	)

	// 判断是否包含结转（定金抵扣、换房结转等）
	const includedCarryForward = computed(() => {
		return list.value.flatMap(o => o.bills).some(o => o.billType === 2) || entity.value.carryForward
	})

	const getRenterContractPreview = () => {
		loadings.calc = true

		const params = {
			isCustomize: 0,
			// 合同id 只在修改重新签约时传
			contractId: entity.value.contractId,
			contractPid: entity.value.contractPid,
			carryForward: entity.value.carryForward,
			carryForwardPrice: Math.abs(entity.value.deductionAmount || 0),
			// 结转方式 1:先抵再折 2:先折再抵(换房先折再抵 其余的先抵再折)
			carryForwardMode: 4 === entity.value.signType ? 2 : 1,
			beginTime: entity.value.beginTime,
			endTime: entity.value.endTime,
			payPattern: entity.value.payPattern,
			payPatternValue: entity.value.payPatternValue,
			depositMonth: entity.value.depositMonth,
			periodMonth: entity.value.periodMonth,
			price: entity.value.price,
			deposit: entity.value.deposit,
			oldDeposit: entity.value.oldDeposit,
			signType: entity.value.signType === 2 ? 2 : 1,
			cycleType: entity.value.cycleType,
			mergeType: entity.value.mergeType,
			otherExpenses: entity.value.otherExpenses,
			zeroRentPeriod: entity.value.zeroRentPeriod,
			houseId: entity.value.houseId,
			contractRentType: entity.value.contractRentType,
			// 手机号判断是否有预定，用于定金抵扣
			phone: entity.value.renterInfo?.phone,
			discountIds: entity.value.discountIds ?? [],
			// 企业合同框架
			contractType: entity.value.contractType
		}

		// 如果是协议框架 传原租金  自定义优惠传现有价格
		if (entity.value.contractType === 4 && entity.value.discountIds?.length && entity.value.discountIds[0] !== '-1') {
			params.price = entity.value.actualPrice
			// params.deposit = Number(entity.value.actualPrice) * Number(entity.value.depositMonth)
		}

		renterContractPreview(params)
			.then(({data = []}) => {
				list.value = data

				console.log(data)
			})
			.finally(() => (loadings.calc = false))
	}

	const onMergeChange = () => {
		entity.value.mergeType = entity.value.mergeType === 3 ? null : 3
		getRenterContractPreview()
	}

	const options = reactive({
		payMethods: []
	})

	// 获取字典
	const getDics = () => {
		settingApi.getDicListByPid(DIC_PID_MAP['PAYMENTMETHOD@PAYMENTMETHOD']).then(({data}) => (options.payMethods = data))
	}

	const billTableOption = reactive<VxeTableProps>({
		size: 'medium',
		rowConfig: {
			isHover: true
		},
		expandConfig: {
			trigger: 'row',
			showIcon: false
		},
		checkboxConfig: {
			checkField: 'isDealWith',
			checkMethod({row}) {
				// 房源定金禁用复选框
				return row.billType !== 2
			}
		}
	})
	const actions: any = {
		// 新签、续签
		1: renterContractInsert,
		2: renterContractInsert,
		// 转租
		3: renterContractSublease,
		// 换房
		4: renterContractChange
	}

	// 提交合同
	const submit = (field: number) => {
		if (field) entity.value.paperNeedSign = true

		let actionType = (entity.value.signType || 1) as number
		let action = actions[actionType]

		// 重置合同或重新提交合同
		if (entity.value.reset || entity.value.resubmit) {
			actionType = 0

			if (entity.value.reset) {
				action = renterContractReset
			} else if (entity.value.resubmit) {
				action = renterContractResubmit
			}
		} else if (actionType > 1) {
			delete entity.value.id
		}

		if (action) {
			list.value
				.flatMap(o => o.bills)
				.forEach(bill => {
					const total = bill.finances.reduce(
						(prev, cur) => {
							prev.occurredMoney += cur.occurredMoney * (cur.feeDirection === 1 ? 1 : -1)
							prev.notOccurredMoney += cur.notOccurredMoney * (cur.feeDirection === 1 ? 1 : -1)
							return prev
						},
						{occurredMoney: 0, notOccurredMoney: 0}
					)

					bill.occurredMoney = Number(total.occurredMoney.toFixed(2))
					bill.notOccurredMoney = Number(total.notOccurredMoney.toFixed(2))
				})

			// 结转抵扣不需要选择支付方式
			if (!includedCarryForward.value) {
				for (let item of list.value) {
					for (const bill of item.bills) {
						// 账单是否已经处理
						bill.isDealWith = Number(bill.isDealWith || 0)
						// billType=2定金账单，无需选择收款方式
						if (bill.isDealWith && !entity.value.paymentMethod) {
							return message.error('已处理账单请选择支付方式')
						}
					}
				}
			}

			const renter = entity.value.renterInfo || {}
			if (XEUtils.isArray(renter.interest)) {
				renter.interest = renter.interest.join('/')
			}
			if (field) {
				loadings.paperSave = true
				loadings.disabledSave = true
			} else {
				loadings.save = true
				loadings.disabledPaperSave = true
			}

			action({
				...entity.value,
				billInfos: list.value
			})
				.then(({data}: any) => {
										emits('success', entity.value.paperNeedSign ? entity.value.paperNeedSign : data)
					message.success('保存成功')
					console.log(data)
					option.onCancel()
				})
				.finally(() => {
					if (field) {
						loadings.disabledSave = true
						loadings.paperSave = false
					} else {
						loadings.save = false
						loadings.disabledPaperSave = true
					}
				})
				.catch(() => {
					loadings.save = false
					loadings.disabledSave = false
					loadings.disabledPaperSave = false
				})
		}
	}
</script>

<style lang="less">
	.renter-bill-preview-dialog {
		.ant-modal-body {
			padding: 0;
			overflow: auto;
			height: 550px;
			position: relative;

			.vxe-toolbar {
				height: 50px;
				border-bottom: 1px solid @border-color-light;
			}

			.bill-table-wrapper {
				padding: 12px;

				.ant-typography:first-of-type blockquote {
					margin-top: 0;
				}

				.bill-preview-table {
					.vxe-table--body-wrapper.body--wrapper,
					.vxe-body--expanded-row {
						min-height: 44px;
					}
					.vxe-body--expanded-column {
						border: none;

						.vxe-table--body-wrapper {
							margin-top: -1px;
							background: rgba(@primary-color, 0.05);

							.vxe-body--column {
								vertical-align: baseline;
							}
						}

						.svg-icon {
							width: 24px;
						}

						.bill-carry-forward-tips {
							left: 4px;
							position: relative;

							&:before {
								content: '';
								width: 8px;
								height: 8px;
								top: 6px;
								left: -4px;
								display: inline-block;
								position: absolute;
								transform: rotate(45deg);
								border: 1px solid transparent;
								background-color: inherit;
								border-left-color: inherit;
								border-bottom-color: inherit;
								border-radius: @border-radius-base;
							}
							&.activity-tag {
								margin-top: 10px;
								&:before {
									top: -5px;
									left: 4px;
									transform: rotate(135deg);
								}
							}
						}
					}
				}
			}
		}
	}

	.tooltip-active-wrapper {
		.ant-tooltip-inner {
			display: flex;
			align-items: center;
			flex-wrap: wrap;
			min-width: 800px;
			.tooltip-active-item {
				height: 30px;
				line-height: 30px;
				padding: 0 10px;
			}
		}
	}
	.footer-tip {
		font-size: 12px;
	}
	.footer-ico {
		font-size: 15px;
		margin-right: 8px;
	}
</style>
